// 订单数据管理
import axios from "axios";
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';

export const useOrderStore = defineStore('order', () => {
  // 订单列表
  const orderList = ref([]);
  // 加载状态
  const loading = ref(false);
  // 错误信息
  const error = ref(null);
  
  // 获取订单列表
  const getOrderList = async () => {
    loading.value = true;
    error.value = null;
    
    try {
      const res = await axios.get('/api/orderList');
      if (res.data.code === 200) {
        orderList.value = res.data.data || [];
        
        // 格式化订单日期
        orderList.value.forEach(order => {
          if (order.orderDate) {
            order.formattedDate = new Date(order.orderDate).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            });
          } else {
            order.formattedDate = '未知日期';
          }
        });
      } else {
        error.value = res.data.message || '获取订单列表失败';
        ElMessage.error(error.value);
      }
    } catch (err) {
      console.error('获取订单列表错误:', err);
      error.value = err.message || '获取订单列表失败';
      ElMessage.error(error.value);
    } finally {
      loading.value = false;
    }
  };
  
  // 删除订单
  const deleteOrder = async (orderId) => {
    if (!orderId) return;
    
    try {
      return await ElMessageBox.confirm(
        '确定要删除此订单吗？此操作不可撤销。',
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const res = await axios.delete(`/api/orderList/${orderId}`);
          if (res.data.code === 200) {
            ElMessage.success('订单删除成功');
            // 重新获取订单列表
            getOrderList();
            return true;
          } else {
            ElMessage.error(res.data.message || '删除订单失败');
            return false;
          }
        } catch (error) {
          console.error('删除订单错误:', error);
          ElMessage.error('删除订单失败: ' + (error.message || '未知错误'));
          return false;
        }
      }).catch(() => {
        // 用户取消删除
        return false;
      });
    } catch (err) {
      console.error('删除订单对话框错误:', err);
      return false;
    }
  };
  
  // 计算属性：订单总数
  const orderCount = computed(() => orderList.value.length);
  
  // 计算属性：已完成订单
  const completedOrders = computed(() => 
    orderList.value.filter(order => order.status === '1')
  );
  
  // 计算属性：待发货订单
  const pendingOrders = computed(() => 
    orderList.value.filter(order => order.status === '0')
  );
  
  // 计算属性：所有订单总金额
  const totalOrderValue = computed(() => {
    return orderList.value.reduce((total, order) => {
      return total + Number(order.totalprice);
    }, 0).toFixed(2);
  });
  
  // 初始加载
  getOrderList();
  
  return {
    orderList,
    loading,
    error,
    getOrderList,
    deleteOrder,
    orderCount,
    completedOrders,
    pendingOrders,
    totalOrderValue
  };
});